package net.wanglu.www.zzz.service.se.poss;

import java.util.HashMap;
import java.util.regex.Pattern;

import net.wanglu.www.zzz.service._Service;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.trees.TreeGraphNode;
import edu.stanford.nlp.trees.TypedDependency;
import edu.stanford.nlp.trees.tregex.TregexMatcher;
import edu.stanford.nlp.trees.tregex.TregexPattern;

public class PossessionExtracter extends _Service {

	@Override
	public Object service(Object... objects) throws Exception {
		// TODO Auto-generated method stub
		HashMap<?, ?> preprocessData = (HashMap<?, ?>) objects[0];
		TypedDependency poss = (TypedDependency) objects[1];

		Tree root = (Tree) preprocessData.get("root");
		
		sb.clear();
		sb.append("/\\bNP\\b/");
		sb.append("<").append("(");
		sb.append("/").append(Pattern.quote(poss.gov().label().tag())).append("/");
		sb.append("<");
		sb.append("/").append(Pattern.quote(poss.gov().label().word())).append("/");
		sb.append(")");
		sb.append("<").append("(");
		sb.append("/").append(Pattern.quote(poss.dep().label().tag())).append("/");
		sb.append("<");
		sb.append("/").append(Pattern.quote(poss.dep().label().word())).append("/");
		sb.append(")");
		TregexPattern pattern = TregexPattern.compile(sb.toString());
		TregexMatcher matcher = pattern.matcher(root);
		Tree ancestor = null;
		if ( matcher.find()) {
			ancestor = matcher.getMatch();
		}
		
		final TreeGraphNode fpossessive = poss.dep();
		final TreeGraphNode fheadword = poss.gov();
		final Tree fAncestor = ancestor;
		final String frelation = poss.reln().getShortName();
		
		return new _PossTuple() {
			{
				this.setAncestor(fAncestor);
				this.setHeadword(fheadword);
				this.setPossessive(fpossessive);
				this.setRelation(frelation);
			}
			@Override
			public Object customize() throws Exception {
				// TODO Auto-generated method stub
				return null;
			}
		};
	}
}
